﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.ControlLib;
using xiaoxiong.KYJControllersLib;
using xiaoxiong.KYJDAL.Services;
using xiaoxiong.ScadaProModbusRtu.childFrm;
using xiaoxiong.ScadaProModbusRtu.Common;
using xiaoxiong.ScadaProModbusRtu.Message.MessageForms;

namespace xiaoxiong.ScadaProModbusRtu
{
    public partial class FrmParamset : Form
    {

        MysqlService mysqlService = new MysqlService();
        public FrmParamset()
        {
            InitializeComponent();



            UpdateTimer = new Timer();
            UpdateTimer.Interval = 200;
            UpdateTimer.Tick += UpdateTimer_Tick;
            UpdateTimer.Start();

            this.FormClosing += (s, e) =>
            {
                UpdateTimer.Stop();
            };

            this.Load += FrmParamset_Load;
        }

        private void FrmParamset_Load(object sender, EventArgs e)
        {
            //配置更新空间状态
            this.tog_AutoLogin.IsChecked = CommonMethods.sysConfig.AutoLogin;
            this.tog_AutoStart.IsChecked = CommonMethods.sysConfig.AutoStart;
            this.tog_AutoLock.IsChecked = CommonMethods.sysConfig.AutoLock;
            this.up_LockPeriod.CurrentValue = CommonMethods.sysConfig.LockPeriod;
            this.up_ShowSeriesCount.CurrentValue = CommonMethods.sysConfig.ShowSeriesCount;
        }

        private Timer UpdateTimer;
        /// <summary>
        /// 控件更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            UpdateCommon(this);
        }


        private void UpdateCommon(Control parentControl)
        {
            if (CommonMethods.plcDevice != null && CommonMethods.plcDevice.IsConnected)
            {
                foreach (Control control in parentControl.Controls)
                {
                    //显示textshow数据
                    if (control is TextSet textSet)
                    {
                        if (textSet.BindVarName.Length > 0 && textSet.BindVarName != null)
                        {
                            float value = 0.0f;
                            if (float.TryParse(CommonMethods.plcDevice[textSet.BindVarName]?.ToString(), out value))
                            {
                                textSet.CurrentValue = value.ToString("f1");
                            }
                        }
                    }
                    else if (control.HasChildren)
                    {
                        UpdateCommon(control);
                    }
                }
            }
        }


        #region 无边框拖动

        //窗体拖动事件
        private bool _isDragging = false;
        private Point _startPoint = new Point(0, 0);
        private void TopPanel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _isDragging = true;
                _startPoint = new Point(e.X, e.Y);
            }
        }

        private void TopPanel_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDragging)
            {
                Point newPoint = this.PointToScreen(new Point(e.X, e.Y));
                this.Location = new Point(newPoint.X - _startPoint.X, newPoint.Y - _startPoint.Y);
            }
        }

        private void TopPanel_MouseUp(object sender, MouseEventArgs e)
        {
            _isDragging = false;
        }
        #endregion
        /// <summary>
        /// 双击修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textSetCommon_ControlDoubleClick(object sender, EventArgs e)
        {
            if (sender is TextSet textSet)
            {
                if (textSet.BindVarName != null && textSet.BindVarName.Length > 0)
                {
                    FrmModify frmModify = new FrmModify(textSet.TitleName,
                        textSet.BindVarName,textSet.CurrentValue);
                    frmModify.ShowDialog();
                }
            }
        }

        /// <summary>
        /// 设置开机自动登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tog_AutoLogin_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveAutoLogin(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOpLog(false,"修改软件自动登录方式：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        /// <summary>
        /// 设置开机自动启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tog_AutoStart_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveAutoStart(((Toggle)sender).IsChecked))
            {
                //写入注册表
                AutoStart(((Toggle)sender).IsChecked);
                CommonMethods.AddOpLog(false, "修改软件自动启动方式：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        /// <summary>
        /// 修改自动锁屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tog_AutoLock_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveAutoLock(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOpLog(false, "修改软件自动锁屏：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        /// <summary>
        /// 锁屏间隔时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void up_LockPeriod_ValueChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveLockPeriod((int)((UpDownLabel)sender).CurrentValue))
            {
                CommonMethods.AddOpLog(false, "修改锁屏间隔时间：" + ((UpDownLabel)sender).CurrentValue.ToString());
                CommonMethods.GetSysConfig();
            }
        }
        /// <summary>
        /// 显示曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void up_ShowSeriesCount_ValueChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveShowSeriesCount((int)((UpDownLabel)sender).CurrentValue))
            {
                CommonMethods.AddOpLog(false, "修改显示曲线：" + ((UpDownLabel)sender).CurrentValue.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        /// <summary>
        /// 修改注册表中的值
        /// </summary>
        /// <param name="isAuto"></param>
        private void AutoStart(bool isAuto = true)
        {
            const string appName = "xiaoxiong.kyj"; // 更改为唯一应用名称
            const string registryRunPath = @"Software\Microsoft\Windows\CurrentVersion\Run";

            try
            {
                using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(registryRunPath, true))
                {
                    if (registryKey == null)
                    {
                        // 注册表路径不存在，可能系统不支持
                        return;
                    }

                    if (isAuto)
                    {
                        // 获取当前应用的可执行文件路径
                        string exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                        // 使用双引号包裹路径，避免空格问题
                        registryKey.SetValue(appName, "\"" + exePath + "\"");
                    }
                    else
                    {
                        // 移除注册表项
                        if (registryKey.GetValue(appName) != null)
                        {
                            registryKey.DeleteValue(appName);
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 无权限访问注册表，可能需要以管理员权限运行
                throw;
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改注册表失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 创建实时的数据表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_CreateTable_Click(object sender, EventArgs e)
        {
            if (new FrmMessageBoxWithoutAck("是否要重新生成数据表?","重新生成").ShowDialog() == DialogResult.OK )
            {
                List<string> columns = new List<string>(){"Id","InsertTime" };
                columns.AddRange(CommonMethods.plcDevice.StoreVarList.Select( c => c.VarName).ToList());
                var result = mysqlService.ReCreateActualTable("ActualData",columns);
                if (result.IsSuccess)
                {
                    CommonMethods.AddOpLog(false, "重新生成实时数据表成功");
                    new FrmMessageBoxWithoutAck("重新生成数据表成功","生成结果提示");
                }
                else
                {
                    CommonMethods.AddOpLog(true, "重新生成实时数据表失败");
                    new FrmMessageBoxWithoutAck("重新生成数据表失败\n" + result.Message, "生成结果提示");
                }
            }
        }
    }
}
